<?php
/**
 * Created by PhpStorm.
 * User: J.H
 * Date: 2018/1/28
 * Time: 2:19
 */

namespace lib\Crypts;


class TripleDES
{

    private $c;

    const DATA_TYPE_HEX = 2;
    const DATA_TYPE_BASE64 = 1;

    /**
     * TripleDES constructor.
     *
     * @param string $crypt_key
     * @param string $method
     * @param false|string $vi
     *
     * @throws
     */
    function __construct(string $crypt_key, $vi = false, $method = 'DES-EDE3')
    {
        $this->c = new OpenSSLCrypt($crypt_key, $method, $vi);
    }

    /**
     * 设置加解密key
     *
     * @param string $crypt_key
     *
     * @return $this
     */
    function setCryptKey(string $crypt_key)
    {
        $this->c->setCryptKey($crypt_key);
        return $this;
    }

    /**
     * 加密
     *
     * @param string $data
     * @param int $return_data
     *
     * @return string
     */
    function encrypt(string $data, $return_data = self::DATA_TYPE_HEX)
    {
        return $this->c->encrypt($this->c->strPad($data), $return_data, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
    }

    /**
     * 解密
     *
     * @param string $data
     * @param int $input_data
     *
     * @return string
     */
    function decrypt(string $data, $input_data = self::DATA_TYPE_HEX)
    {
        return $this->c->strPad($this->c->decrypt($data, $input_data), false);
    }
}